<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <!-- <link href="https://cdn.bootcss.com/element-ui/2.4.5/theme-chalk/index.css" rel="stylesheet"> -->
    <link href="./videojs.css" rel="stylesheet">
    <script src="./videojs.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <script src="./jsonData.js"></script>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        body{
            color: wheat;
            background-color: #1C1F21;
            /*background-color: white;*/
            font-size: 13px;
        }
        li{
            list-style: none;
            line-height: 23px;
            cursor: pointer;
        }
        input{
            outline: none;
        }
        h1{
            margin: auto;
            text-align: center;
            color: white;
            font-size: 32px;
            line-height: 56px;
        }
        .ipt{
            width: 228px;
            background-color: #fff;
            background-image: none;
            border-radius: 4px;
            border: 1px solid #DCDFE6;
            box-sizing: border-box;
            color: #606266;
            display: inline-block;
            font-size: inherit;
            height: 30px;
            line-height: 30px;
            outline: none;
            padding: 0 5px;
        }
        .ipt:focus {
            outline: none;
            border-color: #409EFF;
        }
        .btn{
            height: 30px;
            vertical-align: middle;
            width: 62px;
            border: navajowhite;
            padding: 6px;
            color: white;
            background: #409EFF;
            border-radius: 4px;
        }
        .ul-list{
            padding-left: 8px;
            /*margin-top: 35px;*/
        }
        .videojsBox{
            width: 1200px;
            display: flex;
            display: none;
        }
        .wordWrap{
            /*height: 756px;*/
            height: 710px;
            width: 300px;
            /*border: 1px solid red;*/
            overflow: scroll;
            margin-top: 8px;
        }
        .active{
            color: red;
        }
        .search-active{
            color: red;
        }
        .bg-color{
            background: yellow;
        }
        .black{
            color: black;
        }
        /*显示播放时间和总时间*/
        .video-js .vjs-tech {
            position: relative !important;
        }
        .video-js .vjs-time-control{
            display:block;
        }
        .video-js .vjs-remaining-time{
            display: none;
        }
        /*滚动条样式*/
        ::-webkit-scrollbar {
            width: 0px; /*对垂直流动条有效*/
            height: 0px; /*对水平流动条有效*/
        }
        .search-wrap{
            position: absolute;
            width: 300px;
            margin: 0 auto;
            bottom: 62px;
            margin-left: 8px;
            /*display: none;*/
            z-index: 9999;
        }

        .video-wrap{
            width: 100%;
            height: 100%;
            display: flex;
            background-color: #1C1F21;
        }
        .video-left{
            flex: 60;
            width: 60px;
        }
        .video-main{
            flex: 1500;
            /*background-color: orange;*/
        }
        .video-right{
            flex: 385;
            margin-left: 30px;
        }
        .top{
            height: 62px;
            margin-bottom: 20px;
            background-color: #409EFF;
        }
        .hide{
            visibility: hidden;
        }
        .search-ul-list{
            padding-left: 8px;
        }
        .li-content{
            top: 65px;
            width: 300px;
            /*height: 565px;*/
            margin-top: 35px;
            position: absolute;
            overflow: scroll;
        }
        .searchResultNum{
            position: absolute;
            top: 65px;
            right: 75px;
        }
        .video-js{
            width: 100% !important;
            height: 100% !important;
        }
    </style>
</head>

<body>
    <div class="top">
        <h1>课堂录播系统</h1>
    </div>
    <div class="video-wrap">
        <div class="video-left"></div>
        <div class="video-main">
            <video id="example_video_1" class="video-js vjs-big-play-centered" controls preload="none" poster="./poster.png">
                <source src="./Physics.mp4" type="video/mp4">
            </video>
        </div>
        <div class="video-right">
            <div class="wordWrap">
                <div class="search-wrap">
                    <input type="text" class="ipt" placeholder="请输入要搜索的内容">
                    <input type="button" value="搜索" class="btn">
                </div>
            </div>
            <div class="li-content hide"></div>
            <div class="searchResultNum"></div>
        </div>
    </div>
</body>
<script>
    let $wordWrap = $(".wordWrap");

    let result = [];
    let newMap = {};
    let player = null;
    let deafultNum = 0; //控制高亮
    let autoLang = 0; //控制滚动
    let addDistance = 0; // 拖动进度条字幕跳转
    let resultStr = null;
    let defNum = 0;
    let fDistance = 0;
    let bgColorNum = 0;



    function dataHandle() {
        result = uniArr;
        let fObj = {};
        result = result.reduce((pre, item) => {
            fObj[item.time] ? '' : fObj[item.time] = true && pre.push(item);
            return pre;
        }, [])
        for (var i = 0; i < result.length; i++) {
            result[i].time = getSecound(result[i].time);
            newMap[result[i].time] = result[i];
        }
        let indexD = 0;
        for (key in newMap) {
            newMap[key].index = indexD;
            indexD++;
        }
    }


    // 转换成秒
    function getSecound(minute) {
        let hour = minute.split(':')[0];
        let min = minute.split(':')[1];
        let sec = minute.split(':')[2];
        let secound = Number(hour * 3600) + Number(min * 60) + Number(sec);
        return secound;
    }
    // 转换成分钟单位
    function formatTime(seconds) {
        return [parseInt(seconds / 60 / 60), parseInt(seconds / 60 % 60), parseInt(seconds % 60)]
            .join(":").replace(/\b(\d)\b/g, "0$1");
    }

    let css = {
        wordShow: function(el) {
            el.removeClass('hide');
        },
        wordHide: function(el) {
            el.addClass('hide');
        }
    }

    // 把生成的数据显示到界面上去
    function renderDom() {
        let $ul = $("<ul class='ul-list'></ul>");
        for (let i = 0; i < result.length; i++) {
            let $li = $("<li></li>").text(formatTime(result[i].time) + "\xa0\xa0\xa0\xa0" + result[i].content);
            $ul.append($li);
        }
        $wordWrap.append($ul);
        resultStr = $(".ul-list").html()
    }


    function videoPlayInit() {
        player = videojs('example_video_1', {
            muted: true,
            controls: true / false,
            loop: false,
            muted:false
        });
    }


    // 监听变化
    function timeUpdate() {
        player.on("timeupdate", function(event) {
            var currentTime = parseInt(this.currentTime());
            deafultNum = addDeafultNum(currentTime);
            console.log("timeupdate里的deafultNum", deafultNum);
            $(".wordWrap li").eq(deafultNum - 0).addClass("active");
            $(".wordWrap li").eq(deafultNum - 0).siblings().removeClass("active");
            if (deafultNum) {
                // 343 - 366
                let lastNodeLength = $(".wordWrap li").eq(deafultNum - 1).offset().top;
                let curNodeLength = $(".ul-list .active").eq(0).offset().top;
                let activeScroll = lastNodeLength - curNodeLength;

                let rollDistance = $wordWrap.scrollTop(); //已经滚动距离
                let activeTopDistance = $(".ul-list .active").eq(0).offset().top; //当前高亮距离上边距离

                if (curNodeLength >= 300) { //366
                    autoLang += 30;
                    // $wordWrap.scrollTop(rollDistance + activeTopDistance - 400); //300
                }
                $wordWrap.scrollTop(rollDistance + activeTopDistance - 400); //让文字看板高亮部分一直在中间
            }
        });
    }


    // 监听进度条拖拽
    function seeked() {
        player.on("seeked", function() {
            // 1.先高亮再滚动
            let currentTime = parseInt(this.currentTime());
            let videoPoint = closest(result, currentTime);
            deafultNum = addDeafultNum(videoPoint);
            console.log("seek里的deafultNum", deafultNum);
            $(".wordWrap li").eq(deafultNum - 0).addClass("active");
            $(".wordWrap li").eq(deafultNum - 0).siblings().removeClass("active");
            if ($(".ul-list .active").eq(0)) {
                let rollDistance = $wordWrap.scrollTop(); //已经滚动距离
                let activeTopDistance = $(".ul-list .active").eq(0).offset().top; //当前高亮距离上边距离
                $wordWrap.scrollTop(rollDistance + activeTopDistance - 400);
            } else {
                alert("请耐心等待视频加载完毕")
            }
        })
    }


    //查找时间最近值(包括本身) 
    function closest(arr, num) {
        let latelyTime = result.filter(item => {
            return item.time <= num;
        })
        return latelyTime[latelyTime.length - 1].time; //返回最后一位也就是最近的时间
    }
    // console.log(closest(result, 348)); //350,342



    // 控制显示第几个字幕
    function addDeafultNum(currentTime) {
        // 4  3
        for (key in newMap) {
            if (currentTime === parseInt(key)) {
                return newMap[key].index;
            }
        }
    }

    // 搜索后渲染
    function searchData() {
        $(".wordWrap li").eq(deafultNum - 0).removeClass("active");
        $("li span").removeClass("search-active");
        $("li span").removeClass("bg-color");
        let iptResult = $(".ipt").val();
        let a = new RegExp(iptResult, 'g');
        let str = $(".ul-list").html();
        str2 = str.replace(a, '<span class="search-active">' + iptResult + '</span>'); //每次都给弹力加个span标签（bug）
        if (str != str2) {
            $(".ul-list").html(str2);
            scrollNext(); //滚动距离
        } else {
            alert('没有搜到内容');
            css.wordHide($(".li-content"));
            css.wordShow($(".ul-list"));
        }
    }


    // 搜索关键词
    function searchKeyWord() {
        $(".btn").click(function() {
            searchClick();
            // if ($(".ipt").val()) {
            //     // 重置文字看板
            //     $(".ul-list").html(resultStr);
            //     css.wordHide($(".ul-list"));
            //     css.wordShow($(".li-content"));
            //     $wordWrap.scrollTop(fDistance); //先回到顶部再向下查找，避免出现bug
            //     searchData();
            //     let $searchList = $("<ul class='search-ul-list'></ul>");
            //     for (let i = 0; i < $("li .search-active").parent("li").length; i++) {
            //         let $li = $("<li></li>").html($("li .search-active").parent("li")[i].innerHTML);
            //         $searchList.append($li);
            //     }
            //     $(".li-content").html($searchList);
            // } else {
            //     alert('搜索框内容不能为空')
            // }
        })
    }

    function searchClick(){
            if ($(".ipt").val()) {
                // 重置文字看板
                $(".ul-list").html(resultStr);
                css.wordHide($(".ul-list"));
                css.wordShow($(".li-content"));
                $wordWrap.scrollTop(fDistance); //先回到顶部再向下查找，避免出现bug
                searchData();
                let $searchList = $("<ul class='search-ul-list'></ul>");
                for (let i = 0; i < $("li .search-active").parent("li").length; i++) {
                    let $li = $("<li></li>").html($("li .search-active").parent("li")[i].innerHTML);
                    $searchList.append($li);
                }
                $(".li-content").html($searchList);
            } else {
                alert('搜索框内容不能为空')
            }
    }


    // 输入框为空清空所有样式
    function cleanAllStyle() {
        $(".ipt").keyup(debounce(function() {
            if (!$(this).val()) {
                defNum = 0; // 重置关键词索引,避免关键词一直高亮问题
                $(".ul-list span").removeClass('search-active');
                $(".ul-list span").removeClass('bg-color');
                css.wordHide($(".li-content"));
                css.wordShow($(".ul-list"));
                $(".searchResultNum").html("");
            }
        }, 1000));
    }

    // 防抖
    function debounce(func, wait) {
        let timer;
        return function() {
            let context = this;
            let args = arguments;
            if (timer) clearTimeout(timer);
            timer = setTimeout(() => {
                func.apply(this, args)
            }, wait)
        }
    }

    // 点词切换视频
    function clickWordChangeVideo() {
        $("ul").on('click', '.search-active', function() {
            // 获取这是第几个li
            let liIndex = $(this).parent('li').index();
            let jumpTime = result[liIndex].time; //获取时间节点
            player.currentTime(jumpTime - 0); //定位到字所对应的时间点
        })
    }

    $(".ipt").on('keypress', function(e) {
        if (e.keyCode == 13) {
            if($(".li-content").hasClass('hide')){
                searchClick();
            }else{
                scrollNext();
            }
            
        }
    });

    function scrollNext() {
        console.log(defNum);
        let distanceScroll = $("li .search-active").eq(defNum).offset().top;
        $("li .search-active").eq(defNum).addClass('bg-color');
        $("li .search-active").eq(defNum).parent("li").siblings().find(".search-active").removeClass('bg-color');
        $(".li-content li .search-active").eq(defNum).addClass('bg-color');
        $(".li-content li .search-active").eq(defNum).parent("li").siblings().find(".search-active").removeClass('bg-color');
        //console.log($("li .search-active").eq(0).offset().top); //获取到顶端距离
        let bgColorTimeIndex = $(".bg-color").parent("li").index();
        let bgColorTime = result[bgColorTimeIndex].time;
        debounce(function() {
            player.currentTime(bgColorTime) //定位到高亮字所对应的时间点
        }, 1500)()

        fDistance += distanceScroll - 300;
        autoLang = fDistance; //点击字幕后重新赋值距离
        $wordWrap.scrollTop(fDistance); //滚动代码
        let searchReasultNum = $(".wordWrap li .search-active").length - 1;
        $(".searchResultNum").html((defNum + 1) + "/" + (searchReasultNum + 1));
        if (defNum < searchReasultNum) {
            defNum += 1;
        } else {
            defNum = 0;
        }
    }

    // 点词跳转到视频时间点
    function clickLiChangeVideo() {
        $wordWrap.on("click", 'li', function() {
            // 获取这是第几个li
            let liIndex = $(this).index();
            //获取时间节点
            let activeWordTime = result[liIndex].time;
            player.currentTime(activeWordTime); //定位到字所对应的时间点
        })

    }



    function clickSearchReasultChange() {
        $(".li-content").on("click", 'li', function() {
            // 先添加高亮
            $(this).find(".search-active").addClass('bg-color');
            $(this).find(".search-active").parent("li").siblings().find(".search-active").removeClass('bg-color');
            defNum=$(this).index();
            scrollNext();
            console.log(defNum);

            let str = $(this).text();
            let regRules = /\d{2}:\d{2}:\d{2}/g;
            let activeWordTime = getSecound(regRules.exec(str)[0]);
            player.currentTime(activeWordTime); //定位到字所对应的时间点
        })
    }


    function init() {
        dataHandle();
        renderDom();
        videoPlayInit();
        timeUpdate();
        seeked();
        searchKeyWord();
        cleanAllStyle();
        clickWordChangeVideo();
        clickLiChangeVideo();
        clickSearchReasultChange();
        // console.log(closest(result, 348)); //350,342
        console.log(result);
        console.log(newMap);
    }
    init();


    // $(".wordWrap").scrollTop()//获取已滚动距离
</script>

</html>